<template>
  <layout-card
    ref="layoutRef"
    v-model="search"
    :filters="filterOptions"
    headline="数据筛选"
    headtitle="数据列表"
    @search-change="searchChange"
    @search-reset="searchReset"
  >
    <template #action>
      <el-upload
        ref="importUploadRef"
        :auto-upload="false"
        accept=".xls,.xlsx"
        :show-file-list="false"
        :on-change="importData"
        style="margin-right: 0.75rem; display: inline-block"
      >
        <el-button type="primary">导入</el-button>
      </el-upload>

      <el-button type="primary" @click="templateDownload">模板下载</el-button>
      <el-button type="primary" @click="exportData">导出</el-button>
      <el-button
        type="primary"
        @click="
          router.push({
            name: '/collaborativeCommand/eventEscalation/see',
            query: { id: '', status: '' },
          })
        "
        >上报</el-button
      >
    </template>
    <table-common
      ref="tableRef"
      :columns="loseGoodsColumns"
      :loading="loading"
      :pagination="pager"
      :table-data="tableData"
      size="large"
      @current-change="currentChange"
      @size-change="sizeChange"
      @sort-change="sortChange"
    >
      <template #eventLevel="{ row }">
        <span>{{
          handleTranslate(filterOptions[0].inputProps.options, row.eventLevel)
        }}</span>
      </template>
      <template #processGroup="{ row }">
        <span>{{ row.processGroup.name }}</span>
      </template>
      <template #creator="{ row }">
        <span>{{ row.creator?.name }}</span>
      </template>
      <template #terminal="{ row }">
        <span>{{
          handleTranslate(filterOptions[1].inputProps.options, row.terminal)
        }}</span>
      </template>
      <template #status="{ row }">
        <span>{{
          handleTranslate(filterOptions[7].inputProps.options, row.status)
        }}</span>
      </template>
      <!-- 自定义操作栏示例  -->
      <template #action="{ row }">
        <el-button class="link-btn" @click="openSee(row)" link type="primary"
          >查看</el-button
        >
      </template>
    </table-common>
  </layout-card>
  <el-dialog v-model="seeEventDialog" title="查看已分析事件" width="700px">
    <div>
      <el-form
        :model="infoData"
        autocomplete="off"
        label-position="right"
        label-width="110px"
      >
        <title-dom title="事件上报信息" />
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="发生区域：">
              <span>{{
                handleTranslate(
                  filterOptions[1].inputProps.options,
                  infoData.terminal
                )
              }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="事件地点：">
              <span>{{ infoData.location }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="事件类型：">
              <span>{{
                findTypeName(eventTypes, infoData.eventTypeId)?.join(" - ")
              }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="事件描述：">
              <span>{{ infoData.description }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="发生时间：">
              <span>{{ infoData.eventTime }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="后果/影响：">
              <span>{{ handleTranslate(consequence, infoData.result) }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="来源：">
              <span>{{ infoData.source }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="事件级别：">
              <span>{{
                handleTranslate(
                  filterOptions[0].inputProps.options,
                  infoData.eventLevel
                )
              }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="区域处置单位：">
              <span>{{ infoData.processGroup?.name }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="附件上传：">
              <upload-files
                disabled
                v-model="infoData.files"
                :accept="[
                  'jpg',
                  'jpeg',
                  'png',
                  'gif',
                  'bmp',
                  'svg',
                  'doc',
                  'docx',
                ]"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <title-dom title="事件响应与下发" />
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="后果影响：">
              <span>{{
                handleTranslate(consequence, infoData.approveObj?.result)
              }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="事件级别：">
              <span>{{
                handleTranslate(
                  filterOptions[0].inputProps.options,
                  infoData.approveObj?.eventLevel
                )
              }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="区域处置单位：">
              <span>{{ infoData.approveObj?.processGroup?.name }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="附件上传：">
              <upload-files
                disabled
                v-model="infoData.approveObj.files"
                :accept="[
                  'jpg',
                  'jpeg',
                  'png',
                  'gif',
                  'bmp',
                  'svg',
                  'doc',
                  'docx',
                ]"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="seeEventDialog = false">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onBeforeMount, computed } from "vue";
import LayoutCard from "@/components/LayoutCard/index.vue";
import TableCommon from "@/components/TableCommon/index.vue";
import { filterOptions } from "./config/filter";
import { loseGoodsColumns } from "./config/columns";
import router from "@/router";
import { getResource } from "@/api/resource";
import {
  getEventReportList,
  getEventType,
  eventImport,
  eventExport,
  exportTemplate,
  reportInfo,
  approveInfo,
  getTree,
  getConsequence,
} from "@/api/collaborativeCommand/eventEscalation";
import { getUser } from "@/api/collaborativeCommand/collaborativeDisposal";
import titleDom from "../components/titleDom.vue";
import uploadFiles from "@/components/UploadFiles/index.vue";
import {
  handleTranslate,
  downloadFile,
  findTypeName,
} from "../components/common.js";
import { ElMessage } from "element-plus";
import { useStore } from "vuex";

// 用户信息
const store = useStore();
const userInfo = computed(() => store.state.user.userInfo);
const isManager = store.getters["user/getIsManager"];
const creator = reactive({
  id: userInfo.value.userId,
  name: userInfo.value.name,
  organId: userInfo.value.organId,
  organName: userInfo.value.organName,
});

const seeEventDialog = ref(false);
const infoData = reactive({ approveObj: {} }); //弹窗内容
const tableRef = ref();
const layoutRef = ref();

//表格数据
const tableData = ref([]);
const eventTypes = ref([]); //事件类型
const consequence = ref([]); //后果影响

const loading = ref(false);
// 搜索参数
const search = ref({});
//排序
const order = ref([
  {
    column: "",
    method: "",
  },
]);
const pager = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});
// 前后端分页不统一，特殊处理
const paging = computed(() => {
  return {
    pageNum: pager.currentPage,
    pageSize: pager.pageSize,
    total: pager.total,
  };
});

// 分页
const sizeChange = (size) => {
  pager.pageSize = size;
  loadData();
};
const currentChange = (value) => {
  pager.currentPage = value;
  loadData();
};

/**
 * 打开查看
 */
const openSee = (row) => {
  if (row.status == 20) {
    getInfo(row.id);
    seeEventDialog.value = true;
  } else {
    router.push({
      name: "/collaborativeCommand/eventEscalation/see",
      query: { id: row.id, status: row.status },
    });
  }
};
/**
 * 获取事件上报信息 响应信息
 */
const getInfo = (id) => {
  reportInfo(id).then((res) => {
    if (res.code == 1) {
      Object.assign(infoData, res.data);
      approveInfo({ id: id }).then((res2) => {
        if (res2.code == 1) {
          infoData.approveObj =
            res2.data.find((item) => item.status == 20) || {};
        } else {
          ElMessage.error(res.message || "数据获取失败");
        }
      });
    } else {
      ElMessage.error(res.message || "数据获取失败");
    }
  });
};

/**
 * 导入数据
 */
const importData = (file) => {
  if (!file) {
    return false;
  } else if (!/.(xls|xlsx)$/.test(file.name.toLowerCase())) {
    ElMessage.error("上传格式不正确,请上传xls或者xlsx格式");
    return false;
  }
  const formData = new FormData();
  formData.append("file", file.raw);
  formData.append("name", userInfo.value.name);
  formData.append("organId", userInfo.value.organId);
  formData.append("organName", userInfo.value.organName);
  formData.append("id", userInfo.value.userId);
  eventImport(formData)
    .then((res) => {
      if (res.code == 1) {
        ElMessage.success(res.message || "导入成功");
      } else {
        ElMessage.error(res.message || "导入失败");
      }
    })
    .catch((err) => {
      ElMessage.error(err.message || "导入失败");
    });
};

/**
 * 导出数据
 */
const exportData = () => {
  search.value = layoutRef.value?.getParams();
  eventExport({ ...processParameters(), creator })
    .then((res) => {
      downloadFile(res, "事件上报管理");
    })
    .catch((err) => {
      ElMessage.error(err.message || "导出数据失败");
    });
};
/**
 * 模板下载
 */
const templateDownload = () => {
  exportTemplate()
    .then((res) => {
      downloadFile(res, "事件上报模板");
    })
    .catch((err) => {
      ElMessage.error(err.message || "模板下载失败");
    });
};

/**
 * 加载数据字典
 */
const loadDict = () => {
  Promise.all([
    getResource("event_rules_event_level"),
    getResource("terminals"),
    getEventType(),
    getUser(),
    getTree(),
    getConsequence({ enabled: 1 }),
  ]).then(([res1, res2, res3, res4, res5, res6]) => {
    filterOptions.value[0].inputProps.options = res1.data.properties.meta;
    filterOptions.value[1].inputProps.options = res2.data.properties.meta;
    filterOptions.value[2].inputProps.options = res3.data.map((item) => ({
      value: item.id,
      label: item.name,
    }));
    filterOptions.value[5].inputProps.data = store.state.user.organTree;
    filterOptions.value[6].inputProps.options = res4.data.map((item) => ({
      value: item.userId,
      label: item.name,
    }));
    filterOptions.value[7].inputProps.options = [
      { value: "10", label: "待审核" },
      { value: "11", label: "已回退" },
      { value: "20", label: "已审核" },
    ];
    eventTypes.value = res5.data;
    consequence.value = res6.data?.map((item) => {
      return {
        value: item.id,
        label: item.result,
      };
    });
  });
};

/**
 *  处理搜索参数
 */
const processParameters = () => {
  if (
    Array.isArray(search.value.eventTime) &&
    search.value.eventTime.length > 0
  ) {
    search.value.eventOccurStartTime = search.value.eventTime[0];
    search.value.eventOccurEndTime = search.value.eventTime[1];
  }
  if (
    Array.isArray(search.value.createTime) &&
    search.value.createTime.length > 0
  ) {
    search.value.reportStartTime = search.value.createTime[0];
    search.value.reportEndTime = search.value.createTime[1];
  }
  const obj = {
    ...search.value,
    processGroupId: isManager ? search.value.processGroupId : userInfo.organId,
  };
  obj.creatorName = filterOptions.value[6].inputProps.options?.find(
    (item) => item.value == search.value.creatorName
  )?.label;
  delete obj.eventTime;
  delete obj.createTime;
  return obj;
};

/**
 * 加载表格数据
 */
const loadData = () => {
  loading.value = true;
  const condition = { ...processParameters(), creator, order: order.value };
  if (order.value[0].method == "") {
    delete condition.order;
  }
  getEventReportList({
    ...paging.value,
    condition,
  })
    .then((res) => {
      if (res.data) {
        loading.value = false;
        tableData.value = res.data.list;
        pager.currentPage = res.data.pageNum;
        pager.pageSize = res.data.pageSize;
        pager.total = res.data.total;
      }
    })
    .catch((err) => {
      loading.value = false;
      ElMessage.error(err.message || "获取数据失败");
    });
};
// 排序
const sortChange = (data) => {
  if (data.order) {
    order.value[0].column = data.prop;
    order.value[0].method = data.order == "ascending" ? "asc" : "desc";
  } else {
    order.value[0].column = "";
    order.value[0].method = "";
  }
  loadData();
};

/**
 * 点击查询
 */
const searchChange = (data) => {
  search.value = data;
  loadData();
};

/**
 * 点击重置
 * @param data 数据
 */
const searchReset = (data) => {
  search.value = data;
  pager.currentPage = 1;
  pager.pageSize = 10;
  order.value[0].column = "";
  order.value[0].method = "";
  tableRef.value.clearSort(); //清空排序
  loadData();
};
const initData = () => {
  loadDict();
  loadData();
};
onBeforeMount(initData);
</script>

<style lang="less" scoped></style>
